﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using LSQL;
using System.Net.Sockets;
using System.Net;
using System.Text.RegularExpressions;
using DevExpress.XtraSpreadsheet.Model;
using DevExpress.XtraEditors.Controls;

namespace Shopfloormanagement.Forms
{
    public partial class Login : DevExpress.XtraEditors.XtraForm
    {
        public static Login instance = new Login();
        /// <summary>
        /// 登录时载入数据库SFM，版本更新后为系统数据库
        /// 用于存储工厂和用户信息，其他各工厂的会议信息分别存在对应数据库中，所以需要设定不同的SQL连接语句
        /// SystemInfo中SQL为会议信息连接语句，
        /// SystemInfo中sys为系统信息连接语句。
        /// </summary>
        public Login()
        {
            instance = this;
            InitializeComponent();
        }

        #region 根据IP选择数据库地址
        public static string ip_address = GetLocalIP();

        public static string GetLocalIP()
        {
            try
            {
                string HostName = Dns.GetHostName(); //得到主机名
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    //从IP地址列表中筛选出IPv4类型的IP地址
                    //AddressFamily.InterNetwork表示此IP为IPv4,
                    //AddressFamily.InterNetworkV6表示此地址为IPv6类型
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        return IpEntry.AddressList[i].ToString();
                    }
                }
                return "";
            }
            catch (Exception ex)
            {
                MessageBox.Show("获取本机IP出错:" + ex.Message);
                return "";
            }
        }

        public string Addr;
        private string dbName;
        private void Form_display_Load(object sender, EventArgs e)
        {
            if (ip_address.Substring(0, 3) == "192")
            {
                //公共网路
                Addr = "192.168.1.18";
                SystemInfo.UpdateSQLconnection(Addr, dbName);
            }
            else if (ip_address.Substring(0, 2) == "10")
            {
                //MAHLE内网
                Addr = "10.64.69.235";
                SystemInfo.UpdateSQLconnection(Addr, dbName);
            }
            else
            {
                MessageBox.Show("请正确连接网络");
            }
            txtAccount.Text = Properties.Settings.Default.User;
            txtPwd.Text = Properties.Settings.Default.Pwd;
            DataTable dt = SQL.ReturnDataTable3(SystemInfo.sys, "Factories", $"Del_tag = 0");
            publicFunc.ComboBoxInit(dt, cbFactory, "FactoryName", "ID");
            cbFactory.SelectedIndex = Properties.Settings.Default.Factory;

        }

        #endregion

        private string HashPassword(string password, string salt)
        {
            using (var sha256 = System.Security.Cryptography.SHA256.Create())
            {
                var saltedPassword = password + salt;
                var hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(saltedPassword));
                return BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
            }
        }

        private int factoryID;
        public static int facID = 0;
        private void cbFactory_SelectedValueChanged(object sender, EventArgs e)
        {
            var selectedItem = cbFactory.SelectedItem as publicFunc.ComboBoxItem;
            if (selectedItem != null)
            {
                var tag = selectedItem.Tag; // 这里可以使用tag
                factoryID = Convert.ToInt32(tag);
                facID = Convert.ToInt32(tag);
                Properties.Settings.Default.Factory = cbFactory.SelectedIndex;
                Properties.Settings.Default.Save();
            }
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            string account = txtAccount.Text;
            string pwd = txtPwd.Text;

            string regFac =Regex.Replace(cbFactory.Text, "[^a-zA-Z0-9\\s]", "");
            SystemInfo.readFactory = factoryID;
            dbName = $"SFM_{regFac}";
            SystemInfo.db = dbName;
            SystemInfo.UpdateSQLconnection(Addr, dbName);

            if (string.IsNullOrEmpty(account) || string.IsNullOrEmpty(pwd) || string.IsNullOrEmpty(cbFactory.Text))
            {
                MessageBox.Show("Please input your information");
                return;
            }
            string connectionString = SystemInfo.SQL; // 请替换为实际的数据库连接字符串


            // 获取存储的盐值
            string salt = SQL.InvertedSelect(connectionString, "Employees", $"LoginName = '{account}'", "PasswordSalt");
            if (string.IsNullOrEmpty(salt))
            {
                MessageBox.Show("用户名或密码错误。");
                return;
            }

            // 使用存储的盐值计算哈希密码
            string hashedPassword = HashPassword(pwd, salt);
            string condition = $"LoginName = '{account}' AND PasswordHash = '{hashedPassword}' and Del_tag = 0";
            DataTable userInfo = SQL.ReturnDataTable3(connectionString, "Employees", condition);

            //判断是否查询到用户
            if (userInfo.Rows.Count > 0)
            {
                //查询基础信息
                SystemInfo.userID = (int)userInfo.Rows[0]["ID"];
                SystemInfo.userName = userInfo.Rows[0]["FullName"].ToString();
                SystemInfo.userfactoryID = (int)userInfo.Rows[0]["FactoryID"];


                DataTable dtProperties = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Employees", $"ID={SystemInfo.userID}");
                if (dtProperties.Rows.Count > 0)
                {
                    //正则表达去掉特殊字符！！！！一定要做！
                    SystemInfo.readFactory = factoryID;
                    SystemInfo.readFactoryName = cbFactory.Text;

                    Form_display_Load(sender, e);

                    SystemInfo.depEmployee = SQL.ReturnDataTable3(SystemInfo.SQL, "View_EmployeeDepartments", $"EmployeeID = {SystemInfo.userID} order by departmentLevel desc");
                    if (SystemInfo.depEmployee.Rows.Count > 0)
                    {
                        SystemInfo.readDepartment = (int)SystemInfo.depEmployee.Rows[0]["DepartmentID"];
                        DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "Departments", $"ID = {SystemInfo.readDepartment}");
                        SystemInfo.readparentDep = (int)dt.Rows[0]["ParentDepartmentID"];
                        SystemInfo.readLevel = (int)dt.Rows[0]["departmentLevel"];

                        Console.WriteLine(cbFactory.Properties.Items.Count);
                        Properties.Settings.Default.User = account;
                        Properties.Settings.Default.Pwd = pwd;
                        Properties.Settings.Default.Save();
                        SystemInfo.readFactoryName = cbFactory.Text;

                        this.Hide();
                        DevMainForm.instance.Show();
                        //Shopfloormanagement.PDCA.PDCA.instance.Show();
                    }


                }

            }
            else
            {
                XtraMessageBox.Show("Cannot found an account！", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }

        private void hyperlinkLabelControl1_Click(object sender, EventArgs e)
        {
            bool regist = false;
            DataTable isOnline = SQL.ReturnDataTableAsc(SystemInfo.sys, "Factories", $"FactoryName = '{cbFactory.Text}'");
            if (isOnline.Rows.Count > 0)
            {
                regist = Convert.ToBoolean(isOnline.Rows[0]["isONLINE"]);
                if (regist)
                {
                    registerForm.instance.ShowDialog();
                }
                else
                {
                    MessageBox.Show("You don't have a permission to regist users,\n pls contect system administrator");
                }
            }
            //registerForm.instance.ShowDialog();
        }
    }
}